package crp.core.resource.app;

import com.qwlabs.jackson.Jackson;
import com.qwlabs.lang.C2;
import com.qwlabs.lang.S2;
import com.qwlabs.panache.Where;
import crp.core.resource.domain.models.ResourceWorkflowContextUtil;
import crp.core.workflow.domain.models.WorkflowTaskQuery;
import crp.core.workflow.domain.services.WorkflowQueryConditionBuilder;
import lombok.Getter;
import lombok.Setter;

import javax.enterprise.context.ApplicationScoped;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

@ApplicationScoped
public class ResourceWorkflowQueryCondition implements WorkflowQueryConditionBuilder {
    @Override
    public Boolean support(String code) {
        return "RESOURCE".equals(code);
    }

    @Override
    public Where build(WorkflowTaskQuery query) {
        Condition d = new Condition();
        d.setDepartmentIds(List.of("1"));
        Optional<String> jd = Jackson.write(d);
        Optional<Condition> condition = query.getConditionBy(Condition.class);

        return Where.create()
                .and(keywordLikeCondition(query.getKeyword()))
                .and(departmentIdsInCondition(condition.map(Condition::getDepartmentIds).orElse(null)));
    }


    @Getter
    @Setter
    static class Condition {
        private Collection<String> departmentIds;

    }

    public Where keywordLikeCondition(String keyword) {
        Where where = Where.create();
        if (S2.isBlank(keyword)) {
            return where;
        }
        return Where.create()
                .and(String.format("%s like :keyword", ResourceWorkflowContextUtil.facultyNameQueryKey()),
                        "keyword", "%" + keyword + "%")
                .or(String.format("%s like :keyword", ResourceWorkflowContextUtil.courseNameQueryKey()),
                        "keyword", "%" + keyword + "%");
    }

    public Where departmentIdsInCondition(Collection<String> departmentIds) {
        Where where = Where.create();
        if (C2.isEmpty(departmentIds)) {
            return where;
        }

        return Where.create().and(String.format("%s in :departmentIds",
                        ResourceWorkflowContextUtil.departmentIdQueryKey()),
                "departmentIds", departmentIds);
    }
}
